package com.fly.system.controller;

import com.fly.common.model.SysUserModel;
import com.fly.common.msg.ResultMsg;
import com.fly.common.util.UserlUtil;
import com.fly.system.model.SysMenuModel;
import com.fly.system.service.SysMenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @CLASSNAME: SystemController
 * @author: Fly
 * 日期: 2020/6/13  13:49
 * 描述:系统控制
 **/

@Controller
public class SystemController {

    @Autowired
    private SysMenuService sysMenuService;


    @GetMapping("/login")
    public String getLogin(){
        return "/login";
    }

    @PostMapping("/login")
    @ResponseBody
    public ResultMsg postLogin(SysUserModel user){
        UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName(),user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try{
            subject.login(token);
            return ResultMsg.success();
        }catch (IncorrectCredentialsException e){
            return ResultMsg.error("用户或名密码错误");
        }catch (AuthenticationException e){
            return ResultMsg.error("认证失败请确认用户名密码是否正确");
        }
    }

    @GetMapping("/index")
    public String index(Model model){
        SysUserModel obj = UserlUtil.getUserModel();
        List<SysMenuModel> list = sysMenuService.findMenuListByUserId(obj);
        model.addAttribute("menuList",list);
        model.addAttribute("user",obj);
        return "/index";
    }

    @GetMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        // 退出登录
        subject.logout();
        return "/login";
    }


}
